set more off

local J `1'

local Jminus = `J'-1
forvalues k = 1/`J' {


gen z_`k' = z`k'*ismax

forvalues i=1/5{
replace x`i'_`k' = x`i'_`k'*ismax

replace x`i'_`k' =0 if `k'==altID
}

*Set to 0 for own good

replace z_`k' = 0 if `k'==altID
}

forvalues k = 1/`J' {
gen zorig_`k' = z_`k'
forvalues i=1/5{
gen xorig`i'_`k' = x`i'_`k'
replace x`i'_`k' = bx_`k'*x`i'_`k'
}

replace z_`k' = bz_`k'*z_`k'

}

forvalues k = 1/`J' {


gen zz_`k' = b2z_`k'*z*zorig_`k'

forvalues i=1/5{
gen zx`i'_`k' = b2x_`k'*z*xorig`i'_`k'
}

}

gen zzmax = z*ismax
if(`J'==2) replace zzmax = 0

capture drop bsum b2sum z2sum x2sum
capture drop zzsum zxsum1 zxsum2 zsum xsum1 xsum2  zxzsum zxxsum
gen zzsum = 0
forvalues i=1/5{
gen zxsum`i'=0
}
gen zsum = 0
forvalues i=1/5{
gen xsum`i'=0
}



forvalues k = 1/`J' {
replace zzsum = zzsum + zz_`k'
forvalues i=1/5{
replace zxsum`i' = zxsum`i' + zx`i'_`k'
replace xsum`i' = xsum`i'+ x`i'_`k'
}

replace zsum = zsum+ z_`k'

}

